package generic.rabbitmq;

//import javax.jms.Connection;
import generic.Publisher;

import java.io.IOException;

import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;

public class RabbitMqPublisher implements Publisher {

	Channel channel;

	private String url = "localhost";
	private int port = 5672;
	
	//private final static String QUEUE_NAME = "hello";
	private static final String EXCHANGE_NAME = "logs";
	
	
	private StringBuilder builder;

	public RabbitMqPublisher() {
		super();

		builder = new StringBuilder();

		initialize(url);
		
		System.out.println("RabbitMqPublisher ready to publish messages...");
	}
	
	private void initialize(String brokerUrl) {
		try {
			ConnectionFactory factory = new ConnectionFactory();
		    factory.setHost(url);
		    factory.setPort(port);
		    Connection connection = factory.newConnection();
		    channel = connection.createChannel();
		    
		    //channel.queueDeclare(QUEUE_NAME, false, false, false, null);
		    channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean send(String message) {
		boolean result = false;
		try {
			channel.basicPublish(EXCHANGE_NAME, "", null, message.getBytes());
			result = true;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}

}
